import React, { Component } from 'react'
import PubSub from "pubsub-js";

export default class Search extends Component {

    search = async () => {
        const { keyWordElement: { value: keyWord } } = this;

        PubSub.publish('search-state', {
            isFirst: false,
            isLoading: true
        });

        // 使用fetch 发送请求 (未优化的代码)
        // fetch(`https://api.github.com/search/users?q=${keyWord}`).then(resp => {
        //     // console.log(resp);
        //     return resp.json();     // 请求成功返回携带相应数据的 Promise
        // }, err => {
        //     console.log("请求服务器出现错误!", err);
        // }).then(resp => {
        //     console.log(resp);
        //     PubSub.publish('search-state', {isFirst: false, isLoading: false, users: resp.items});
        // }, err => {
        //     console.log("获取数据失败!", err);
        //     PubSub.publish('search-state', {isLoading: false, err: err.message});
        // })

        // 优化后的代码
        try {
            const resp = await fetch(`https://api.github.com/search/users?q=${keyWord}`)
            const data = await resp.json();
            PubSub.publish('search-state', {isFirst: false, isLoading: false, users: data.items});
        } catch (err) {
            PubSub.publish('search-state', {isLoading: false, err: err.message});
        }

    }

    render() {
        return (
            <section className="jumbotron">
                <h3 className="jumbotron-heading">搜索 Github 用户</h3>
                <div>
                    <input ref={c => this.keyWordElement = c} type="text" placeholder="请输入关键词点击搜索" />&nbsp;
                    <button onClick={this.search}>搜索</button>
                </div>
            </section>
        )
    }
}
